/*
 * Copyright (c) 2011  Cristian Constantin
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package com.quizio.dao.generic;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.List;

/**
 * @author Cristian Constantin
 * @since 30.11.2010
 */
public class HibernateGenericDao<T> extends HibernateDaoSupport implements GenericDao<T> {

    private Class<T> persistentClass;

    public HibernateGenericDao() {
        this.persistentClass = (Class<T>) ((ParameterizedType) getClass().
                getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @Autowired
    public void init(SessionFactory factory) {
        this.setSessionFactory(factory);
    }

    public void save(T t) {
        this.getHibernateTemplate().save(t);
    }

    public void update(T t) {
        this.getHibernateTemplate().update(t);
    }

    public void saveOrUpdate(T t) {
        this.getHibernateTemplate().saveOrUpdate(t);
    }

    public void saveOrUpdateAll(Collection entities) {
        this.getHibernateTemplate().saveOrUpdateAll(entities);
    }

    public T getById(Long id) {
        return (T) this.getHibernateTemplate().get(persistentClass, id);
    }

    public void delete(T t) {
        this.getHibernateTemplate().delete(t);
    }

    public List<T> getAll() {
        return super.getHibernateTemplate().find("from " + persistentClass.getSimpleName());
    }

    protected T findFirst(String queryString, Object value) {
        List list = super.getHibernateTemplate().find(queryString, value);

        return (list == null || list.size() == 0) ? null : (T) list.get(0);
    }

    protected T findFirst(String queryString, Object... values) {
        List list = super.getHibernateTemplate().find(queryString, values);

        return (list == null || list.size() == 0) ? null : (T) list.get(0);
    }

}
